import React, { useState, useRef, useEffect } from "react";
import { Button, Tag, NavBar, Space, Swiper, Toast, Radio } from 'antd-mobile';
import { message } from "antd";
import styles from './Me.module.css';
import http from '../utils/http';
import { useNavigate, useParams } from "react-router-dom";

export default function Xiangqing() {

    const navigate = useNavigate();
    // const { id } = useParams();
    const [detailData, setDetailData] = useState(null); // 初始值设为 null
    const [selectedSize, setSelectedSize] = useState('');
    const [isInCart, setIsInCart] = useState(false);
    let [id, setId] = useState(localStorage.getItem('id') ? localStorage.getItem('id') : 0);

    console.log(id);

    const getDetailData = async () => {
        const res = await http.post(`/detail`, { _id: id });
        setDetailData(res.data.data);
    };

    useEffect(() => {
        getDetailData();
    }, []);

    let alipayForm = useRef();



    // 轮播图图片地址数组，可替换为实际图片地址
    const imgUrls = [
        '../1.jpg',
        '../2.jpg',
        '../3.jpg'
    ];
    const items = imgUrls.map((imgUrl, index) => (
        <Swiper.Item key={index}>
            <img
                src={imgUrl}
                alt={`手机壳图片 ${index + 1}`}
                className={styles.slideImg}
            />
        </Swiper.Item>
    ));

    const handleAddToCart = () => {
        if (selectedSize) {
            setIsInCart(true);
            Toast.show('已加入购物车');
        } else {
            Toast.show('请选择尺码');
        }
    };

    // 生成订单号的函数
    const generateOrderNumber = () => {
        const timestamp = new Date().toISOString().replace(/[-:.TZ]/g, ''); // 获取当前时间的ISO格式并去除分隔符
        const randomPart = Math.floor(Math.random() * 10000).toString().padStart(4, '0'); // 生成一个4位随机数
        return `ORD${timestamp}${randomPart}`; // 返回订单号，格式为 ORD + 时间戳 + 随机数
    };

    const alipay = () => {
        console.log("🚀 ~ alipay ~ id:", id);

        // 生成订单号
        const orderNumber = generateOrderNumber();
        console.log("Generated Order Number:", orderNumber);

        // 将订单号存储到 localStorage 或传递给后端
        localStorage.setItem('orderNumber', orderNumber);

        // 调用支付宝接口
        http.post('/alipay', { ...detailData, out_trade_no: orderNumber })
            .then(res => {
                console.log("🚀 ~ alipay ~ res.data:", res.data);
                alipayForm.current.innerHTML = res.data;
                document.forms[0].submit();
            })
            .catch(err => {
                console.error("支付宝接口调用失败:", err);
                Toast.show('支付失败，请稍后再试');
            });
    };
    const back = () => {
        navigate(-1)
    }
    // Toast.show({
    //   content: '点击了返回区域',
    //   duration: 1000,
    // })
    return (
        <div>
            <div ref={alipayForm} style={{ display: 'none' }}></div>

            <NavBar onBack={back}>详情</NavBar>
            {/* 轮播图部分 */}
            <Swiper
                loop
                autoplay
            >
                {items}
            </Swiper>

            {/* 商品价格及销量等信息部分 */}
            <div className={styles.priceAndSaleInfo}>
                <span className={styles.discountedPrice}>热销款券后 ¥{detailData?.price}</span>
                <span className={styles.soldQuantity}>已售 {detailData?.soldQuantity}+</span>
            </div>
            {/* 商品标题 */}
            <h2 className={styles.productTitle}>
                {detailData?.title}
            </h2>
            {/* 商品介绍部分 */}
            <p className={styles.productIntroduction}>
                {detailData?.description}
            </p>
            {/* 优惠信息 */}
            <div>
                店铺优惠: &nbsp;&nbsp;&nbsp;<Tag color='red' fill='outline'>
                    {detailData?.couponInfo}
                </Tag>
            </div>
            {/* 功能及售后信息部分 */}
            <div className={styles.featuresAndAfterSale}>
                <div className={styles.delivery}>
                    <span>配&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;送 : </span>
                    {detailData?.deliveryInfo?.map((item, index) => (
                        <Tag color="gray" fill='outline' key={index}>{item}</Tag>
                    ))}
                </div>
                <div className={styles.afterSale}>
                    <span>售&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;后: </span>
                    {
                        detailData?.guarantee?.map((item, index) => (
                            <Tag color="gray" fill='outline' key={index}>{item}</Tag>
                        ))
                    }
                </div>
                {/* 尺码选择部分 */}
                <div className={styles.sizeSection}>
                    <h2>选择尺码</h2>
                    <div className={styles.changeradio}>
                        <Radio.Group value={selectedSize}
                            onChange={(value) => setSelectedSize(value)}
                        >
                            {detailData?.sizes?.map((size) => (
                                <Radio key={size} value={size}>
                                    {size}
                                </Radio>
                            ))}
                        </Radio.Group>
                    </div>
                </div>
                {/* 操作按钮部分 */}

            </div>
            <Space className={styles.actionButtons}>
                <Button color='warning' onClick={handleAddToCart}>加入购物车</Button>
                <Button color='danger' onClick={async () => {

                    if (selectedSize) {
                        setIsInCart(true);
                        message.success('正在跳转支付页面');
                        alipay()
                    } else {
                        Toast.show('请选择尺码加入购物车');
                        return
                    }



                }}>付款</Button>

            </Space>
        </div>
    );
}

